package top.yeyusmile.service;

import com.google.gson.Gson;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.yeyusmile.common.MyTemplate;
import top.yeyusmile.mirai.Sender;
import top.yeyusmile.mirai.msg.MusicShareMsg;
import top.yeyusmile.mirai.msg.PlainMsg;
import top.yeyusmile.mirai.msg.XmlMsg;
import top.yeyusmile.pojo.KuWoSearchResult;
import top.yeyusmile.pojo.NetEaseResult;
import top.yeyusmile.utils.HttpUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 夜雨
 * @Web www.yeyusmile.top
 * @date 2022/3/15 23:41
 */

@Service
public class DianGeServiceImpl implements DianGeService {

    @Autowired
    private final MyTemplate myTemplate;

    //private MyQQMessage myQQMessage;

    // private KuWoSearchResult result;


    public DianGeServiceImpl(MyTemplate myTemplate) {
        this.myTemplate = myTemplate;
    }

    @Override
    public void diange(Sender sender, String msg) {

        try {
            String url = "http://search.kuwo.cn/r.s?all=" + URLEncoder.encode(msg.replaceAll("点歌", ""), "utf-8") + "&ft=music&itemset=web_2013&client=kt&pn=0&rn=1&rformat=json&encoding=utf8";
            HttpUtil.httpGet(url, "", new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    System.out.println(e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    KuWoSearchResult result = new Gson().fromJson(response.body().string(),
                            KuWoSearchResult.class);
                    System.out.println(result);
                    //System.out.println(response.body().string());
                    getMp3(result, sender);

                }
            });


           /* try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析mp3地址
     *
     * @param result
     */
    private void getMp3(KuWoSearchResult result, Sender sender) {

        if (result != null && result.getList() != null) {
            String musicId = result.getList().get(0).getMusicId();
            String artist = result.getList().get(0).getArtist();
            String name = result.getList().get(0).getName();
            try {
                String url = "http://antiserver.kuwo.cn/anti.s?response=url&rid=" + musicId + "&format=mp3&type=convert_url";
                HttpUtil.httpGet(url, "", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //System.out.println(response.body().string());
                        //sendXml(response.body().string(), artist, name, sender);//发送xml音乐卡片消息
                        //xml失效。以文字显示
                        List<Object> params = new ArrayList<>();
                        // params.add(new PlainMsg(name + "\n" + artist + "\n" + response.body().string()));
                        String mp3url = response.body().string();
                        System.out.println("mp3地址：" + mp3url);
                        MusicShareMsg musicShareMsg = new MusicShareMsg("KugouMusic", name, artist,
                                mp3url, "http://imge.kugou.com/stdmusic/120/20220622/20220622210310914827.jpg",
                                mp3url, "[分享]" + name);
                        params.add(musicShareMsg);
                        System.out.println("mp3发送：" + musicShareMsg);
                        myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
                    }
                });


               /* try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 发送xml音乐卡片消息
     *
     * @param mp3url 音乐地址
     * @param artist 作者
     * @param name   歌名
     */
    private void sendXml(String mp3url, String artist, String name, Sender sender) {
        String xmlMsg = String.format("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID=\"2\" templateID=\"1\" action=\"web\" brief=\"Music\" sourceMsgId=\"0\" url=\"\" flag=\"0\" adverSign=\"0\" multiMsgFlag=\"0\"><item layout=\"2\"><audio cover=\"\" src=\"%s\" /><title>%s</title><summary>%s</summary></item><source name=\"\" icon=\"\" action=\"\" appid=\"-1\" /></msg>", mp3url, name, artist);
        List<Object> params = new ArrayList<>();
        params.add(new XmlMsg(xmlMsg));
        myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
    }


    //网易
    @Override
    public void netEase(Sender sender, String msg) throws UnsupportedEncodingException {
        try {
            String url = "https://music.cyrilstudio.top/search?keywords=" + URLEncoder.encode(msg.replaceAll("点歌", ""), "utf-8");
            HttpUtil.httpGet(url, "", new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String jsonStr = response.body().string();
                    NetEaseResult result = new Gson().fromJson(jsonStr,
                            NetEaseResult.class);
                    System.out.println(result);

                    List<Object> params = new ArrayList<>();
                    String name = result.getResult().getSongs().get(0).getName();
                    Long id = result.getResult().getSongs().get(0).getId();
                    String mp3url = "http://music.163.com/song/media/outer/url?id=" + (id + "").trim() + ".mp3";
                    System.out.println("mp3地址：" + mp3url);
                    MusicShareMsg musicShareMsg = new MusicShareMsg("NeteaseCloudMusic", name, name,
                            mp3url, "http://p1.music.126.net/rQufRu0Ls4TJLVBymbs75g==/109951167173296114.jpg?param=130y130",
                            mp3url, "[分享]" + name);
                    params.add(musicShareMsg);
                    System.out.println("mp3发送：" + musicShareMsg);
                    myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());

                }
            });

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
